import { app, BrowserWindow, BrowserWindowConstructorOptions, dialog, Menu, MenuItem, MenuItemConstructorOptions } from 'electron'
import { CommonWindowOptionsType } from '@/types/type'
import path from 'path'


let menuConfigs: MenuItemConstructorOptions[] = [];

function createCommonWindow(options: CommonWindowOptionsType): BrowserWindow {
    const defaultWebPreferences: BrowserWindowConstructorOptions['webPreferences'] = {
        // 打开调试工具
        devTools: true,
        // 预加载脚本路径
        preload: path.join(__dirname, './preload/preload.js'),
        // 启用上下文隔离
        contextIsolation: true,
        // 禁用 Node 集成（安全要求）    
        nodeIntegration: false,
        // 启用沙盒模式
        sandbox: true,
    }

    // 合并配置参数
    const mergedOptions: BrowserWindowConstructorOptions = {
        width: 1200,
        height: 800,
        webPreferences: {
            ...defaultWebPreferences,
            ...options.webPreferences
        },
        ...options
    }

    // 应用平台特定覆盖配置
    const platform = process.platform;
    if (options.platformOverrides?.[platform as keyof typeof options.platformOverrides]) {
        Object.assign(mergedOptions, options.platformOverrides[platform as keyof typeof options.platformOverrides]);
    }

    // 创建窗口实例
    const win = new BrowserWindow(mergedOptions)

    // 处理模态窗口特殊逻辑
    if (options.modal && options.parent) {
        if (platform === 'darwin') {
            // macOS特殊处理
            win.setAlwaysOnTop(true, 'modal-panel')
            // options.parent.setEnabled(false)
            win.on('close', () => {
                options.parent?.setEnabled(true)
            })
        }
    }

    // 开发环境加载 Vite 服务
    if (process.env.NODE_ENV === 'development' && options.devUrl) {
        win.loadURL(options.devUrl).catch(err => {
            console.error('Failed to load dev URL:', err)
            app.quit()
        })
        // win.webContents.openDevTools({ mode: 'bottom' })
    } else {
        win.loadFile(path.join(__dirname, '../index.html'), {
            hash: options.prodPath // 生产环境使用 hash 路由
        }).catch(err => {
            console.error('Failed to load production file:', err)
        })
    }

    return win
}


// 创建窗口函数
function createWindow(): BrowserWindow {
    const mainWindow = createCommonWindow({
        devUrl: 'http://localhost:5173'
    })

    addMenuConfig({
        label: 'Tools',
        id: 'tools',
        submenu: [
            {
                // 主线程主动发送消息给渲染进程
                click: () => mainWindow.webContents.send('update-counter', 1),
                label: 'Increment'
            },
            {
                click: () => mainWindow.webContents.send('update-counter', -1),
                label: 'Decrement'
            }
        ]
    })

    // 处理窗口关闭事件
    mainWindow.on('close', (e) => {
        e.preventDefault(); // 阻止默认关闭行为
        console.log('窗口即将关闭');
        const choice = dialog.showMessageBoxSync(mainWindow, {
            type: 'question',
            buttons: ['yes', 'no'],
            title: '退出',
            message: '确定要退出应用程序吗？',
        });
        if (choice === 0) {
            mainWindow.destroy(); // 用户确认后关闭窗口
        }
    });

    return mainWindow;
}

// 添加菜单配置
const addMenuConfig = (menuConfig: MenuItemConstructorOptions) => {
    let found = false;

    menuConfigs.forEach(config => {
        if (config.id === menuConfig.id) {
            found = true;
            if (config.submenu && menuConfig.submenu && Array.isArray(menuConfig.submenu) && Array.isArray(config.submenu)) {
                config.submenu.push(...menuConfig.submenu);
            } else {
                config.submenu = menuConfig.submenu;
            }
        }
    });

    if (!found) {
        menuConfigs.push(menuConfig);
    }
}


const createToolWindow = (parent: BrowserWindow) => {
    let win: BrowserWindow = createCommonWindow({
        width: 375,
        height: 545,
        parent: parent,
        modal: true,
        title: '计算器',
        resizable: false,
        // 隐藏菜单栏 macos无效
        autoHideMenuBar: true,
        // 显示标题栏和边框
        frame: true,
        backgroundColor: '#2c3e50',
        platformOverrides: {
            darwin: {
                // 模态窗口
                modal: false, // 禁用默认 Sheet 样式
                titleBarStyle: 'default', // 显式设置标题栏样式（macOS） 
            }
        },
        devUrl: 'http://localhost:5173/calculator',
        prodPath: '#/calculator'
    })

    return win;
}

const toolMenu = (parent: BrowserWindow) => {
    addMenuConfig({
        label: 'Tools',
        id: 'tools',
        submenu: [
            { type: 'separator' },
            {
                label: '计算器',
                click: () => {
                    createToolWindow(parent);
                },
                // 添加快捷键
                accelerator: 'CommandOrControl+T'
            }
        ]
    })
}

const buildMenu = () => {
    const existingMenu = Menu.getApplicationMenu();
    const menu = existingMenu ? existingMenu : Menu.buildFromTemplate(menuConfigs);

    if (existingMenu) {
        menuConfigs.forEach(config => menu.append(new MenuItem(config)));
    }

    Menu.setApplicationMenu(menu);
};


// 右键菜单
const contextMenuTemplate: MenuItemConstructorOptions[] = [
    {
        label: '复制',
        accelerator: 'CommandOrControl+C',
        click: () => {
            console.log('复制操作');
        },
        role: 'copy'
    },
    {
        label: '粘贴',
        accelerator: 'CommandOrControl+V',
        click: () => {
            console.log('粘贴操作');
        },
        role: 'paste'
    }
];

const contextMenu = Menu.buildFromTemplate(contextMenuTemplate);

const createContextMenu = (window: BrowserWindow) => {
    contextMenu.popup({ window: window });
}

export { createWindow, toolMenu, buildMenu, createContextMenu } 